package com.axin.auth.handle;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSONObject;
import com.axin.common.core.domain.web.AjaxResult;
import com.axin.common.core.utils.ServletUtils;
import com.axin.common.security.model.LoginUser;
import com.axin.common.security.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义退出处理类 返回成功
 *
 * @Author axin
 * @Date 2021/10/17 15:55
 **/
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Autowired
    private TokenService tokenService;

    /**
     * 退出处理
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (ObjectUtil.isNotNull(loginUser)) {
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            // asyncService.recordLogininfor(userName, Constants.LOGOUT, "退出成功", request);
        }
        ServletUtils.renderString(response, JSONObject.toJSONString(AjaxResult.error(HttpStatus.HTTP_OK, "退出成功")));
    }
}
